#include "messageshowarea.h"

MessageShowArea::MessageShowArea()
{
    //设置基本显示
    container = new QWidget();
    this->setWidgetResizable(true);
    this->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    this->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal{height:0px;}");
    this->verticalScrollBar()->setStyleSheet("QScrollBar:vertical{width:2px; background-color:rgb(191,189,187);}");
    this->setWidget(container);

    //设置布局管理器
    QVBoxLayout* layout = new QVBoxLayout();
    layout->setSpacing(0);
    layout->setContentsMargins(0,0,0,0);
    container->setLayout(layout);
}

void MessageShowArea::addMessage(bool isLeft, const model::Message &message)
{
    MessageItem* item = MessageItem::makeMessageItem(isLeft,message);
    container->layout()->addWidget(item);
}

void MessageShowArea::addFrontMessage(bool isLeft, const model::Message &message)
{
    MessageItem* item = MessageItem::makeMessageItem(isLeft,message);
    dynamic_cast<QVBoxLayout*>(container->layout())->insertWidget(0,item);
}

void MessageShowArea::clear()
{
    QLayout* layout = container->layout();
    for(int i = layout->count()-1;i>=0;i--)
    {
        QLayoutItem* item = layout->takeAt(i);
        if(item->widget()) delete item->widget();
        delete item;
    }
}

void MessageShowArea::srcollToEnd()
{
    QTimer* timer = new QTimer();
    connect(timer, &QTimer::timeout, this, [=]() {
        // 获取到垂直滚动条的最大值
        int maxValue = this->verticalScrollBar()->maximum();
        // 设置滚动条的滚动位置
        this->verticalScrollBar()->setValue(maxValue);

        timer->stop();
        timer->deleteLater();
    });
    timer->start(500);
}
